package com.csj.picture.controller;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.csj.picture.common.BaseResponse;
import com.csj.picture.common.ResultUtils;
import com.csj.picture.model.dto.picture.pictureResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.HashMap;

@RestController
public class classifybirdController {

    @PostMapping("/classify")
    public BaseResponse<String> classifyImage(@RequestParam String imageUrl) throws IOException {
            // 下载图片
            File tempFile = File.createTempFile("temp", ".jpg");
            URL url = new URL(imageUrl);
            try (InputStream in = url.openStream();
                 ReadableByteChannel rbc = Channels.newChannel(in);
                 FileOutputStream fos = new FileOutputStream(tempFile)) {
                fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            }
            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("file", tempFile);
            // 发送 HTTP POST 请求
            String result = HttpUtil.post("http://localhost:5000/predict", paramMap);

            // 解析 JSON 结果
            pictureResult pictureResult = JSONUtil.toBean(result, pictureResult.class);

            // 删除临时文件
            tempFile.delete();

            return ResultUtils.success(pictureResult.getClass_name());

    }

}


